/**
 * XDevice 分布式存储库实现
 * 
 * 适配层：提供类POSIX接口，隐藏分布式实现细节
 * 通过Mock底层API模拟Raft一致性协议和分布式复制
 */

#define _DEFAULT_SOURCE  /* for usleep */

#include <libxdevice.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include <pthread.h>

/* ========== 内部数据结构 ========== */

/* 简单的内存存储结构 */
#define MAX_DATA_SIZE (10 * 1024 * 1024)  // 10MB per device
typedef struct {
    char* data;
    size_t allocated_size;
} device_storage_t;

/* 设备描述符信息 */
typedef struct {
    int fd;
    char name[256];
    int flags;
    off_t position;
    uint64_t size;
    int replicas;
    int is_open;
    device_storage_t storage;  // 内存存储
} device_info_t;

/* 集群状态 */
static struct {
    int initialized;
    int cluster_health;
    int node_count;
    int leader_available;
    char leader_id[64];
    uint64_t raft_term;
    uint64_t raft_index;
} cluster_state = {0};

/* 设备描述符表 */
#define MAX_DEVICES 32
static device_info_t device_table[MAX_DEVICES];
static pthread_mutex_t device_mutex = PTHREAD_MUTEX_INITIALIZER;

/* ========== Mock底层分布式API ========== */

/* 模拟Raft一致性协议的写入操作 */
static int internal_xdevice_raft_write(const char* device_name, const void* data, 
                                       size_t size, off_t offset, int sync_mode,
                                       device_storage_t* storage) {
    printf("  [RAFT] 提交写入到Leader: 设备=%s, 偏移=%ld, 大小=%zu\n", 
           device_name, offset, size);
    
    // 确保存储空间足够
    size_t required_size = offset + size;
    if (required_size > storage->allocated_size) {
        size_t new_size = ((required_size / MAX_DATA_SIZE) + 1) * MAX_DATA_SIZE;
        char* new_data = realloc(storage->data, new_size);
        if (!new_data) {
            printf("  [RAFT] 内存分配失败\n");
            return XDEVICE_ENOMEM;
        }
        // 初始化新分配的内存
        if (storage->data == NULL) {
            memset(new_data, 0, new_size);
        } else {
            memset(new_data + storage->allocated_size, 0, new_size - storage->allocated_size);
        }
        storage->data = new_data;
        storage->allocated_size = new_size;
        printf("  [RAFT] 扩展存储空间到 %zu 字节\n", new_size);
    }
    
    // 实际写入数据到内存存储
    memcpy(storage->data + offset, data, size);
    printf("  [RAFT] 数据已写入内存存储\n");
    
    // 模拟Raft日志追加延迟
    usleep(5000);  // 5ms
    
    printf("  [RAFT] Leader日志追加完成，开始副本同步...\n");
    
    // 模拟副本同步过程
    int replicas = 3;  // 默认3副本
    for (int i = 1; i <= replicas; i++) {
        printf("  [RAFT] 同步到副本%d/3...", i);
        fflush(stdout);
        
        usleep(2000);  // 模拟网络延迟
        
        printf(" 完成\n");
    }
    
    cluster_state.raft_index++;
    
    if (sync_mode == XDEVICE_WRITE_FSYNC) {
        printf("  [RAFT] 强制同步模式：等待所有副本确认...\n");
        usleep(10000);  // 额外同步延迟
        printf("  [RAFT] 所有副本已确认，写入操作完成\n");
    } else if (sync_mode == XDEVICE_WRITE_SYNC) {
        printf("  [RAFT] 同步模式：等待多数派确认...\n");
        usleep(5000);
        printf("  [RAFT] 多数派已确认，写入操作完成\n");
    } else {
        printf("  [RAFT] 异步模式：Leader确认后立即返回\n");
    }
    
    return XDEVICE_OK;
}

/* 模拟一致性读取操作 */
static int internal_xdevice_consistent_read(const char* device_name, void* buffer,
                                           size_t size, off_t offset, int consistency,
                                           device_storage_t* storage) {
    if (consistency == XDEVICE_CONSISTENCY_STRONG) {
        printf("  [READ] 强一致性读取：从Leader读取最新数据\n");
        usleep(3000);
    } else if (consistency == XDEVICE_CONSISTENCY_QUORUM) {
        printf("  [READ] 仲裁读取：从多数派确认数据一致性\n");
        usleep(8000);
    } else {
        printf("  [READ] 最终一致性：从本地副本读取\n");
        usleep(1000);
    }
    
    // 检查存储是否已初始化
    if (!storage->data || offset >= storage->allocated_size) {
        printf("  [READ] 读取位置超出存储范围或存储未初始化，填充零\n");
        memset(buffer, 0, size);
        return size;  // 返回请求的字节数，用零填充
    }
    
    // 计算实际可读取的字节数
    size_t available = storage->allocated_size - offset;
    size_t to_read = (size < available) ? size : available;
    
    // 从内存存储读取实际数据
    memcpy(buffer, storage->data + offset, to_read);
    
    // 如果读取不足，填充零
    if (to_read < size) {
        memset((char*)buffer + to_read, 0, size - to_read);
    }
    
    printf("  [READ] 从存储读取 %zu 字节 (请求 %zu 字节)\n", to_read, size);
    
    return size;  // 总是返回请求的大小，包括零填充的部分
}

/* 模拟健康检查 */
static int internal_xdevice_health_check(void) {
    // 模拟集群健康检查
    cluster_state.cluster_health = 1;
    cluster_state.node_count = 3;
    cluster_state.leader_available = 1;
    strcpy(cluster_state.leader_id, "node-1");
    cluster_state.raft_term = 5;
    
    return XDEVICE_OK;
}

/* 模拟设备元数据获取 */
static int internal_xdevice_get_device_info(const char* device_name, xdevice_stat_t* stat) {
    strcpy(stat->name, device_name);
    stat->size = 1024 * 1024 * 1024;  // 1GB默认大小
    stat->blksize = 4096;
    stat->blocks = stat->size / stat->blksize;
    stat->replicas = 3;
    stat->healthy_replicas = 3;
    stat->ctime = time(NULL);
    stat->mtime = time(NULL);
    stat->atime = time(NULL);
    stat->mode = 0644;
    
    return XDEVICE_OK;
}

/* ========== 工具函数 ========== */

static int allocate_fd(void) {
    pthread_mutex_lock(&device_mutex);
    for (int i = 0; i < MAX_DEVICES; i++) {
        if (!device_table[i].is_open) {
            device_table[i].is_open = 1;
            device_table[i].fd = i + 100;  // 避免与系统fd冲突
            pthread_mutex_unlock(&device_mutex);
            return device_table[i].fd;
        }
    }
    pthread_mutex_unlock(&device_mutex);
    return XDEVICE_ERROR;
}

static device_info_t* get_device_info(xdevice_fd_t fd) {
    for (int i = 0; i < MAX_DEVICES; i++) {
        if (device_table[i].is_open && device_table[i].fd == fd) {
            return &device_table[i];
        }
    }
    return NULL;
}

static void free_fd(xdevice_fd_t fd) {
    pthread_mutex_lock(&device_mutex);
    for (int i = 0; i < MAX_DEVICES; i++) {
        if (device_table[i].fd == fd) {
            // 释放存储内存
            if (device_table[i].storage.data) {
                free(device_table[i].storage.data);
            }
            device_table[i].is_open = 0;
            memset(&device_table[i], 0, sizeof(device_info_t));
            break;
        }
    }
    pthread_mutex_unlock(&device_mutex);
}

/* ========== 公共API实现 ========== */

// POSIX友好接口适配层命名空间隔离
// 例如：int lx_init(const char* config_path) { return xdevice_init(config_path); }
// 其它API同理，后续可全部通过xdevice_*实现

int lx_init(const char* config_path) {
    return xdevice_init(config_path);
}

void lx_cleanup(void) {
    xdevice_cleanup();
}

const char* lx_version(void) {
    return xdevice_version();
}

lx_fd_t lx_open(const char* device_name, int flags, uint64_t size) {
    return xdevice_open(device_name, flags, size);
}

int lx_close(lx_fd_t fd) {
    return xdevice_close(fd);
}

ssize_t lx_pwrite(lx_fd_t fd, const void* buf, size_t count, off_t offset) {
    return xdevice_pwrite(fd, buf, count, offset);
}

ssize_t lx_pread(lx_fd_t fd, void* buf, size_t count, off_t offset) {
    return xdevice_pread(fd, buf, count, offset);
}

ssize_t lx_write(lx_fd_t fd, const void* buf, size_t count) {
    return xdevice_write(fd, buf, count);
}

ssize_t lx_read(lx_fd_t fd, void* buf, size_t count) {
    return xdevice_read(fd, buf, count);
}

off_t lx_lseek(lx_fd_t fd, off_t offset, int whence) {
    return xdevice_lseek(fd, offset, whence);
}

int lx_fsync(lx_fd_t fd) {
    return xdevice_fsync(fd);
}

int lx_fstat(lx_fd_t fd, xdevice_stat_t* stat) {
    return xdevice_fstat(fd, stat);
}

int lx_health_check(xdevice_health_t* health) {
    return xdevice_health_check(health);
}

const char* lx_strerror(int error_code) {
    return xdevice_strerror(error_code);
}

/* 文件描述符验证宏实现 */
int xdevice_fd_valid(xdevice_fd_t fd) {
    return get_device_info(fd) != NULL;
}
